<?php

namespace app\models\db;

use yii\db\ActiveRecord;
use app\models\db\Role;
use app\models\db\FunctionPoint;

class RoleFunctionPointRelation extends ActiveRecord
{
	public static function tableName()
	{
		return '{{t_role_function_point_relation}}';
	}

	public function rules()
	{
		return [
			['role_id', 'exist', 'targetClass' => Role::className(), 'targetAttribute' => 'id', 'message' => '角色不存在'],
			['function_point_id', 'validateFunctionPoint', 'message' => '功能点不存在'],
			[['role_id', 'function_point_id'], 'unique', 'targetAttribute' => ['role_id', 'function_point_id'], 'message' => '关系已存在'],
		];
	}

	/**
	 * 验证功能点
	 * 只有控制器和动作同时存在的才能通过
	 * @param  int $attr function_point_id
	 * @param  [type] $params [description]
	 * @return bool
	 * @author milloc
	 * @date   2018-04-26
	 */
	public function validateFunctionPoint($attr, $params)
	{
		$count = FunctionPoint::find()->where(['id' => $attr, 'is_deleted' => FunctionPoint::IS_DELETED_NO])->andWhere('(not isnull(`controller`) and `controller` <> "") and (not isnull(`action`) and `action` <> "")')->count();
		return $count > 0;
	}

	/**
	 * 保存
	 * 同时删除没有传入的值
	 * @param  int $role_id
	 * @param  array|int $function_point_id
	 * @return bool
	 * @author milloc
	 * @date   2018-04-25
	 */
	public static function saveRoleFunctionPoint($role_id, $function_point_id)
	{
		$get_arr = is_array($function_point_id) ? $function_point_id : [$function_point_id];
		$ori_arr = self::find()->select('function_point_id')->where(['role_id' => $role_id])->asArray()->column();

		$save_arr = array_diff($get_arr, $ori_arr);
		$del_arr = array_diff($ori_arr, $get_arr);

		if (empty($save_arr) && empty($del_arr)) {
			return true;
		}

		$res = true;
		self::getDb()->transaction(function () use ($save_arr, $del_arr, $role_id, &$res) {
			if (!empty($del_arr)) {
				$res = RoleFunctionPointRelation::deleteAll(['role_id' => $role_id, 'function_point_id' => $del_arr]);
				if ($res === false) {
					throw new \Exception('failed to delete');
					return;
				}
			}

			foreach ($save_arr as $function_point) {
				$obj = new RoleFunctionPointRelation;
				$obj->role_id = $role_id;
				$obj->function_point_id = $function_point;
				$res = $obj->save();
				if ($res === false) {
					throw new \Exception('failed to save');
					break;
				}
			}
		});

		return $res;
	}
}